<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Workerman\Worker;

class mqtt extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'mqtt {action}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'PHP Server MQTT Client';

    protected $client_id = 'php-server';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        global $argv;
        $arg = $this->argument('action');
        $argv[1]=$arg;

        $worker=new Worker();
        $worker->count=1;
        $worker->onWorkerStart=function(){
            $mqtt=new \Workerman\Mqtt\Client("mqtt://".env('MQTT_HOST').":".env('MQTT_PORT'),array(
                //'ssl'=>array(
                //'local_cert'=>base_path().'/path/mqtt/client.crt',
                //'local_pk'=>base_path().'/path/mqtt/client.key',
                //'cafile'=>base_path().'/path/mqtt/ca.crt',
                //'verify_peer'=>false,
                //'allow_self_signed'=>true,
                //),
                //$mqtt->transport='ssl';
                'username'=>env('MQTT_USER'),
                'password'=>env('MQTT_PASSWORD'),
                'debug'=>env('MQTT_DEBUG'),
                'client_id'=>$this->client_id.mt_rand(0,999),
                'will'=>[
                    'topic'=>'status/'.$this->client_id,
                    'content'=>0,
                    'qos'=>2,
                    'retain'=>true,
                ]
            ));
            $mqtt->onConnect=function($mqtt){
                $mqtt->subscribe('/iot/#');
            };
            $mqtt->onMessage=function($topic,$data,$mqtt){
                var_dump($topic);
                var_dump($data);
                //TODO 业务代码

                //publish消息到topic
                $mqtt->publish('test','helloworkermanmqtt');
            };
            $mqtt->connect();
        };
        Worker::runAll();
    }
}
